﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web;
using System.Web.Hosting;
using System.IO;

namespace GroupChat2013.Logic
{
    public class WinAppTypeFinder : AppDomainTypeFinder
    {
        #region Fields

        private bool _ensureBinFolderAssembliesLoaded = true;
        private bool _binFolderAssembliesLoaded = false;

        /// <summary>
        /// 插件文件夹名称
        /// </summary>
        private readonly string PluginDicName = "Plugins";

        #endregion

        #region Ctor

        public WinAppTypeFinder() { }

        #endregion

        #region Properties

        public bool EnsureBinFolderAssembliesLoaded
        {
            get { return _ensureBinFolderAssembliesLoaded; }
            set { _ensureBinFolderAssembliesLoaded = value; }
        }

        #endregion

        #region Methods

        public virtual string GetBinDirectory()
        {
            //not hosted. For example, run either in unit tests
            return AppDomain.CurrentDomain.BaseDirectory;
        }

        public override IList<Assembly> GetAssemblies()
        {
            if (this.EnsureBinFolderAssembliesLoaded && !_binFolderAssembliesLoaded)
            {
                _binFolderAssembliesLoaded = true;
                string binPath = GetBinDirectory();
                binPath = Path.Combine(binPath, PluginDicName);
                if (!Directory.Exists(binPath))
                {
                    Directory.CreateDirectory(binPath);
                }

                LoadMatchingAssemblies(binPath);
            }

            return base.GetAssemblies();
        }

        #endregion
    }
}
